var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js');
var user = require('../db/userSql.js');
var QcloudSms = require("qcloudsms_js");
let jwt = require('jsonwebtoken');
//引入支付宝配置文件
const alipaySdk = require('../db/alipay.js');
const AlipayFormData = require('alipay-sdk/lib/form').default;
//引入axiso
const axios = require('axios');


function getTimeToken(exp) {

  let getTime = parseInt(new Date().getTime() / 1000);
  console.log(getTime, exp);
  return getTime - exp > 60 * 3600


}

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});


//支付状态
router.post('/api/successPayment', function (req, res, next) {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //订单号
  let out_trade_no = req.body.out_trade_no;
  let trade_no = req.body.trade_no;
  //支付宝配置
  const formData = new AlipayFormData();
  // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
  formData.setMethod('get');
  //支付时信息
  formData.addField('bizContent', {
    out_trade_no,
    trade_no
  });
  //返回promise
  const result = alipaySdk.exec(
    'alipay.trade.query', {}, { formData: formData },
  );
  //后端请求支付宝
  result.then(resData => {
    axios({
      method: 'GET',
      url: resData
    }).then(data => {
      let responseCode = data.data.alipay_trade_query_response;
      if (responseCode.code == '10000') {
        switch (responseCode.trade_status) {
          case 'WAIT_BUYER_PAY':
            res.send({
              data: {
                code: 0,
                data: {
                  msg: '支付宝有交易记录，没付款'
                }
              }
            })
            break;

          case 'TRADE_CLOSED':
            res.send({
              data: {
                code: 1,
                data: {
                  msg: '交易关闭'
                }
              }
            })
            break;

          case 'TRADE_FINISHED':
            connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
              //用户id
              let uId = results[0].id;
              connection.query(`select * from store_order where uId = ${uId} and order_id = ${out_trade_no}`, function (err, result) {
                let id = result[0].id;
                //订单的状态修改掉2==》3
                connection.query(`update store_order set order_status = replace(order_status,'2','3') where id = ${id}`, function () {
                  res.send({
                    data: {
                      code: 2,
                      data: {
                        msg: '交易完成'
                      }
                    }
                  })
                })
              })
            })
            break;

          case 'TRADE_SUCCESS':
            connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
              //用户id
              let uId = results[0].id;
              connection.query(`select * from store_order where uId = ${uId} and order_id = ${out_trade_no}`, function (err, result) {
                let id = result[0].id;
                //订单的状态修改掉2==》3
                connection.query(`update store_order set order_status = replace(order_status,'2','3') where id = ${id}`, function () {
                  res.send({
                    data: {
                      code: 2,
                      data: {
                        msg: '交易完成'
                      }
                    }
                  })
                })
              })
            })
            break;
        }
      } else if (responseCode.code == '40004') {
        res.send({
          data: {
            code: 4,
            msg: '交易不存在'
          }
        })
      }
    }).catch(err => {
      res.send({
        data: {
          code: 500,
          msg: '交易失败',
          err
        }
      })
    })
  })
})
//发起支付
router.post('/api/payment', function (req, res, next) {
  //订单号
  let orderId = req.body.orderId;
  //商品总价
  let price = req.body.price;
  //购买商品的名称
  let name = req.body.name;
  //开始对接支付宝API
  const formData = new AlipayFormData();
  // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
  formData.setMethod('get');
  //支付时信息
  formData.addField('bizContent', {
    outTradeNo: orderId, //订单号
    productCode: 'FAST_INSTANT_TRADE_PAY', //写死的
    totalAmount: price, //价格
    subject: name, //商品名称
  });
  //支付成功或者失败跳转的链接
  formData.addField('returnUrl', 'http://localhost:8080/payment');
  //返回promise
  const result = alipaySdk.exec(
    'alipay.trade.page.pay', {}, { formData: formData },
  );
  //对接支付宝成功，支付宝方返回的数据
  result.then(resp => {
    res.send({
      data: {
        code: 200,
        success: true,
        msg: '支付中',
        paymentUrl: resp
      }
    })
  })
})

//修改订单状态
router.post('/api/submitOrder', function (req, res, next) {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //订单号
  let orderId = req.body.orderId;
  //购物车选中的商品id
  let shopArr = req.body.shopArr;
  //查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uId = results[0].id;
    connection.query(`select * from store_order where uId = ${uId} and order_id = ${orderId}`, function (err, result) {
      //订单的数据库id
      let id = result[0].id;
      //修改订单状态 1==>2
      connection.query(`update store_order set order_status = replace(order_status,'1','2') where id = ${id}`, function (e, r) {
        //购物车数据删除
        shopArr.forEach(v => {
          connection.query(`delete from goods_cart where id = ${v}`, function () {

          })
        })
        res.send({
          data: {
            code: 200,
            success: true
          }
        })
      })
    })
  })

})
//查询订单
router.post('/api/selectOrder', function (req, res, next) {
  //接收前端给后端的订单号
  let orderId = req.body.orderId;
  connection.query(`select * from store_order where order_id='${orderId}'`, function (err, result) {
    res.send({
      data: {
        success: true,
        code: 200,
        data: result
      }
    })
  })
})
//生成一个订单
router.post('/api/addOrder', function (req, res, next) {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //前端给后端的数据
  let goodsArr = req.body.arr;
  //生成订单号order_id，规则：时间戳 + 6为随机数
  function setTimeDateFmt(s) {
    return s < 10 ? '0' + s : s
  }

  function randomNumber() {
    const now = new Date();
    let month = now.getMonth() + 1;
    let day = now.getDate();
    let hour = now.getHours();
    let minutes = now.getMinutes();
    let seconds = now.getSeconds();
    month = setTimeDateFmt(month);
    day = setTimeDateFmt(day);
    hour = setTimeDateFmt(hour);
    minutes = setTimeDateFmt(minutes);
    seconds = setTimeDateFmt(seconds);
    let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
    return orderCode;
  }
  /*
  未支付：1
  待支付：2
  支付成功：3
  支付失败：4 | 0
  */
  //商品列表名称
  let goodsName = [];
  //订单商品总金额
  let goodsPrice = 0;
  //订单商品总数量
  let goodsNum = 0;
  //订单号
  let orderId = randomNumber();

  goodsArr.forEach(v => {
    goodsName.push(v.goods_name);
    goodsPrice += v.goods_price * v.goods_num;
    goodsNum += parseInt(v.goods_num);
  })
  //查询当前用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uId = results[0].id;
    connection.query(`insert into store_order (order_id,goods_name,goods_price,goods_num,order_status,uId) values ('${orderId}','${goodsName}','${goodsPrice}','${goodsNum}','1',${uId})`, function () {

      connection.query(`select * from store_order where uId = ${uId} and order_id='${orderId}'`, function (err, result) {
        res.send({
          data: {
            success: true,
            code: 200,
            data: result
          }
        })
      })
    })
  })

})
//删除收货地址
router.post('/api/deleteAddress', function (req, res, next) {
  let id = req.body.id;
  connection.query(`delete from address where id = ${id}`, function (error, results) {
    res.send({
      data: {
        code: 200,
        success: true,
        msg: '删除成功'
      }
    })
  })
})
//修改收货地址
router.post('/api/updateAddress', function (req, res, next) {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //拿到前端给后端传入的数据
  let body = req.body;
  let [id, name, tel, province, city, county, addressDetail, isDefault, areaCode] = [
    body.id,
    body.name,
    body.tel,
    body.province,
    body.city,
    body.county,
    body.addressDetail,
    body.isDefault,
    body.areaCode
  ];
  //查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uId = results[0].id;
    //对应查询到0 或者 1 有没有默认收货地址
    connection.query(`select * from address where uId = ${uId} and isDefault = ${isDefault}`, function (err, result) {
      if (result.length > 0) {
        let addressId = result[0].id;
        connection.query(`update address isDefault = replace(isDefault,'1','0') where id = ${addressId}`, function (e, r) {
          let updateSql = `update address set uId = ? , name = ? , tel = ? , province = ? , city = ? ,county = ? , addressDetail = ? , isDefault = ? , areaCode = ? where id = ${id}`;
          connection.query(updateSql, [uId, name, tel, province, city, county, addressDetail, isDefault, areaCode], function (errors, datas) {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: '修改成功'
              }
            })
          })
        })
      } else {
        let updateSql = `update address set uId = ? , name = ? , tel = ? , province = ? , city = ? ,county = ? , addressDetail = ? , isDefault = ? , areaCode = ? where id = ${id}`;
        connection.query(updateSql, [uId, name, tel, province, city, county, addressDetail, isDefault, areaCode], function (errors, datas) {
          res.send({
            data: {
              code: 200,
              success: true,
              msg: '修改成功'
            }
          })
        })
      }
    })
  })
})
//查询收货地址
router.post('/api/selectAddress', function (req, res, next) {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);

  //查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uId = results[0].id;
    connection.query(`select * from address where uId = ${uId}`, function (err, result) {
      res.send({
        data: {
          code: 200,
          success: true,
          msg: '查询成功',
          data: result
        }
      })
    })
  })
})
//新增收货地址
router.post('/api/addAddress', function (req, res, next) {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //拿到前端给后端传入的数据
  let body = req.body;
  let [name, tel, province, city, county, addressDetail, isDefault, areaCode] = [
    body.name,
    body.tel,
    body.province,
    body.city,
    body.county,
    body.addressDetail,
    body.isDefault,
    body.areaCode
  ];

  //查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uId = results[0].id;
    //增加一条收货地址
    if (isDefault != 1) {
      connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values (${uId},"${name}","${tel}","${province}","${city}","${county}","${addressDetail}","${isDefault}","${areaCode}")`, function (err, result) {
        res.send({
          data: {
            code: 200,
            success: true,
            msg: '收货地址添加成功'
          }
        })
      })
    } else {

      connection.query(`select * from address where uId = ${uId} and isDefault = ${isDefault}`, function (err, result) {
        if (result.length > 0) {
          let addressId = result[0].id;
          connection.query(`update address set isDefault = replace(isDefault,'1','0') where id = ${addressId}`, function () {
            connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values (${uId},"${name}","${tel}","${province}","${city}","${county}","${addressDetail}","${isDefault}","${areaCode}")`, function (e, r) {
              res.send({
                data: {
                  code: 200,
                  success: true,
                  msg: '收货地址添加成功'
                }
              })
            })
          })
        } else {
          connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values (${uId},"${name}","${tel}","${province}","${city}","${county}","${addressDetail}","${isDefault}","${areaCode}")`, function (err, result) {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: '收货地址添加成功'
              }
            })
          })
        }
      })

    }
  })
})
//修改购物车数量
router.post('/api/updateNum', function (req, res, next) {

  let id = req.body.id;
  let changeNum = req.body.num;

  connection.query(`select * from goods_cart where id = ${id}`, function (error, results) {
    //原来的数量
    let num = results[0].goods_num;
    connection.query(`update goods_cart set goods_num = replace(goods_num,${num},${changeNum}) where id = ${id}`, function (err, result) {
      res.send({
        data: {
          code: 200,
          success: true
        }
      })
    })

  })

})
//删除购物车数据
router.post('/api/deleteCart', function (req, res, next) {

  let arrId = req.body.arrId;

  for (let i = 0; i < arrId.length; i++) {
    connection.query(`delete from goods_cart where id = ${arrId[i]}`, function (error, results) {
      res.send({
        data: {
          code: 200,
          success: true,
          msg: '删除成功'
        }
      })
    })
  }
})

//查询购物车数据
router.post('/api/selectCart', function (req, res, next) {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uId = results[0].id;
    //查询购物车
    connection.query(`select * from goods_cart where uId = ${uId}`, function (err, result) {
      res.send({
        data: {
          code: 200,
          success: true,
          data: result
        }
      })
    })
  })
})
//添加购物车数据
router.post('/api/addCart', function (req, res, next) {
  //后端接收前端的参数
  let goodsId = req.body.goodsId;
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);

  //如果执行，就证明token过期了
  if (getTimeToken(tokenObj.exp)) {
    res.send({
      data: {
        code: 1000
      }
    })
  }

  //查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uId = results[0].id;
    //查询商品
    connection.query(`select * from goods_list where id=${goodsId}`, function (err, result) {
      let goodsName = result[0].name;
      let goodsPrice = result[0].price;
      let goodsImgUrl = result[0].imgUrl;
      //查询当前用户在之前是否添加过本商品
      connection.query(`select * from goods_cart where uId=${uId} and goods_id=${goodsId}`, function (e, r) {
        //用户之前是添加过商品到购物车
        if (r.length > 0) {
          let num = r[0].goods_num;
          connection.query(`update goods_cart set goods_num = replace(goods_num,${num},${parseInt(num) + 1}) where id = ${r[0].id}`, function (e, datas) {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: '添加成功'
              }
            })
          })
        } else {
          //没有
          connection.query(`insert into goods_cart (uId,goods_id,goods_name,goods_price,goods_num,goods_imgUrl) values ("${uId}","${goodsId}","${goodsName}","${goodsPrice}","1","${goodsImgUrl}")`, function () {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: '添加成功'
              }
            })
          })
        }
      })
    })
  })
})
//修改密码
router.post('/api/recovery', function (req, res, next) {
  let params = {
    userTel: req.body.phone,
    userPwd: req.body.pwd
  }
  //查询用户是否存在
  connection.query(user.queryUserTel(params), function (error, results) {
    //某一条记录数id
    let id = results[0].id;
    let pwd = results[0].pwd;
    console.log(`update user set pwd = replace(pwd,${pwd},${params.userPwd}) where id = ${id}`)
    connection.query(`update user set pwd = replace(pwd,'${pwd}','${params.userPwd}') where id = ${id}`, function (err, result) {
      res.send({
        code: 200,
        data: {
          success: true,
          msg: '修改成功'
        }
      })
    })
  })
})

//查询用户是否存在
router.post('/api/selectUser', function (req, res, next) {

  let params = {
    userTel: req.body.phone
  }
  //查询用户是否存在
  connection.query(user.queryUserTel(params), function (error, results) {
    if (results.length > 0) {
      res.send({
        code: 200,
        data: {
          success: true
        }
      })
    } else {
      res.send({
        code: 0,
        data: {
          success: false,
          msg: '此用户不存在'
        }
      })
    }
  })
})
//注册
router.post('/api/register', function (req, res, next) {
  let params = {
    userTel: req.body.phone,
    userPwd: req.body.pwd
  }
  //查询用户是否存在
  connection.query(user.queryUserTel(params), function (error, results) {
    if (error) throw error;
    //用户存在
    if (results.length > 0) {
      res.send({
        code: 200,
        data: {
          success: true,
          msg: '登录成功',
          data: results[0]
        }
      })
    } else {
      //不存在，新增一条数据
      connection.query(user.inserData(params), function (err, result) {
        connection.query(user.queryUserTel(params), function (e, r) {
          res.send({
            code: 200,
            data: {
              success: true,
              msg: '登录成功',
              data: r[0]
            }
          })
        })
      })
    }
  })
})

//增加一个用户
router.post('/api/addUser', function (req, res, next) {

  let params = {
    userTel: req.body.phone
  }
  //查询用户是否存在
  connection.query(user.queryUserTel(params), function (error, results) {
    if (error) throw error;
    //用户存在
    if (results.length > 0) {
      res.send({
        code: 200,
        data: {
          success: true,
          msg: '登录成功',
          data: results[0]
        }
      })
    } else {
      //不存在，新增一条数据
      connection.query(user.inserData(params), function (err, result) {
        connection.query(user.queryUserTel(params), function (e, r) {
          res.send({
            code: 200,
            data: {
              success: true,
              msg: '登录成功',
              data: r[0]
            }
          })
        })
      })
    }
  })
})
//发送短信验证码
router.post('/api/code', function (req, res, next) {

  let tel = req.body.phone;

  // 短信应用SDK AppID
  var appid = 1400187558; // SDK AppID是1400开头

  // 短信应用SDK AppKey
  var appkey = "dc9dc3391896235ddc2325685047edc7";

  // 需要发送短信的手机号码
  var phoneNumbers = [tel];

  // 短信模板ID，需要在短信应用中申请
  var templateId = 285590; // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请

  // 签名
  var smsSign = "三人行慕课"; // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`

  // 实例化QcloudSms
  var qcloudsms = QcloudSms(appid, appkey);

  // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
  function callback(err, ress, resData) {
    if (err) {
      console.log("err: ", err);
    } else {
      res.send({
        code: 200,
        data: {
          success: true,
          data: ress.req.body.params[0]
        }
      })
    }
  }

  var ssender = qcloudsms.SmsSingleSender();
  //这个变量：params 就是往手机上，发送的短信
  var params = [Math.floor(Math.random() * (9999 - 1000)) + 1000];
  ssender.sendWithParam(86, phoneNumbers[0], templateId,
    params, smsSign, "", "", callback); // 签名参数不能为空串

})

//登录
router.post('/api/login', function (req, res, next) {
  //后端要接收前端传递过来的值
  let params = {
    userTel: req.body.userTel,
    userPwd: req.body.userPwd
  };

  let userTel = params.userTel;
  let userPwd = params.userPwd || '666666';
  //引入token包
  let jwt = require('jsonwebtoken');
  //用户信息
  let payload = { tel: userTel };
  //口令
  let secret = 'xiaoluxian';
  //生成token
  let token = jwt.sign(payload, secret, {
    expiresIn: 3600
  });

  //查询用户手机号是否存在
  connection.query(user.queryUserTel(params), function (error, results) {
    //手机号存在 
    if (results.length > 0) {
      //记录的id
      let id = results[0].id;

      connection.query(user.queryUserPwd(params), function (err, result) {
        if (result.length > 0) {
          connection.query(`update user set token = '${token}' where id = ${id}`, function () {
            //手机号和密码都对
            res.send({
              code: 200,
              data: {
                success: true,
                msg: '登录成功',
                data: result[0]
              }
            })
          })

        } else {
          //密码不对
          res.send({
            code: 302,
            data: {
              success: false,
              msg: '密码不正确'
            }
          })
        }
      })

    } else {
      //不存在
      res.send({
        code: 301,
        data: {
          success: false,
          msg: '手机号不存在'
        }
      })
    }
  })
})


//查询商品id的数据
// router.get('/api/goods/id', function (req, res, next) {
//     let id = req.query.id;
//     connection.query('select * from goods_list where id=' + id + '', function (error, results) {
//         if (error) throw error;
//         res.json({
//             code: 0,
//             data: results[0]
//         })
//     })
// })

// 分类的接口
router.get('/api/goods/list', function (req, res, next) {

  res.send({
    code: 0,
    data: [{
      //一级
      id: 0,
      name: '推荐',
      data: [{
        //二级
        id: 0,
        name: '推荐',
        list: [
          //三级
          {
            id: 0,
            name: '铁观音',
            imgUrl: 'https://img1.baidu.com/it/u=3747685723,2990729760&fm=253&fmt=auto&app=138&f=JPEG?w=499&h=319'
          },
          {
            id: 1,
            name: '桂花乌龙',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fgfs2.gomein.net.cn%2FT1sTdQBsLv1RCvBVdK_800.jpg%3Fv%3D1&refer=http%3A%2F%2Fgfs2.gomein.net.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668328697&t=5d28d38435a54a539e7fe193504a590a'
          },
          {
            id: 3,
            name: '铁饼',
            imgUrl: 'https://img1.baidu.com/it/u=1261732135,3102544786&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          },
          {
            id: 4,
            name: '紫砂壶',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg1.99114.com%2Fgroup1%2FM00%2FA0%2F38%2FwKgGTFj-sAiABvbFAABn0Ztao7E348.jpg&refer=http%3A%2F%2Fimg1.99114.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668330033&t=00f6b23aea225e2eb792e9005e01e068'
          },
          {
            id: 5,
            name: '龙井',
            imgUrl: 'https://img0.baidu.com/it/u=3949428449,236506462&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          },
          {
            id: 6,
            name: '武夷岩茶',
            imgUrl: 'https://img2.baidu.com/it/u=2739632429,2905552780&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          },
          {
            id: 7,
            name: '茶杯',
            imgUrl: 'https://img0.baidu.com/it/u=588003752,2654544099&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=329'
          },
          {
            id: 8,
            name: '茶宠',
            imgUrl: 'https://img1.baidu.com/it/u=2899686954,2272268307&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          },
        ]
      }]
    },
    {
      //一级
      id: 1,
      name: '绿茶',
      data: [{
        //二级
        id: 1,
        name: '绿茶',
        list: [
          //三级
          {
            id: 0,
            name: '龙井',
            imgUrl: 'https://img0.baidu.com/it/u=174149987,3233167841&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=300'
          },
          {
            id: 1,
            name: '碧螺春',
            imgUrl: 'https://img0.baidu.com/it/u=1153313524,113282652&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333'
          },
          {
            id: 3,
            name: '雀舌',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.huohuasai.org.cn%2Fcha%2FupFiles%2FinfoImg%2Fcoll%2F20200328%2FOT20200328131758774.jpg&refer=http%3A%2F%2Fwww.huohuasai.org.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668328521&t=8a4adb6f968e97f1e639283ff157b24a'
          },
          {
            id: 4,
            name: '安吉白茶',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbkimg.cdn.bcebos.com%2Fpic%2F8b13632762d0f703eacc038a07fa513d2697c56e&refer=http%3A%2F%2Fbkimg.cdn.bcebos.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668328659&t=bcded8e8c859e0cac2001263fd0f5810'
          },
          {
            id: 5,
            name: '六安瓜片',
            imgUrl: 'https://img2.baidu.com/it/u=1214526775,209022228&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          }
        ]
      }]
    },
    {
      //一级
      id: 2,
      name: '乌龙',
      data: [{
        //二级
        id: 3,
        name: '乌龙',
        list: [
          //三级
          {
            id: 0,
            name: '桂花乌龙',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fgfs2.gomein.net.cn%2FT1sTdQBsLv1RCvBVdK_800.jpg%3Fv%3D1&refer=http%3A%2F%2Fgfs2.gomein.net.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668328697&t=5d28d38435a54a539e7fe193504a590a'
          },
          {
            id: 1,
            name: '武夷山',
            imgUrl: 'https://img2.baidu.com/it/u=863998337,2107768256&fm=253&fmt=auto&app=138&f=JPEG?w=540&h=413'
          },
          {
            id: 3,
            name: '梨山茶',
            imgUrl: 'https://img2.baidu.com/it/u=2309971899,3968066275&fm=253&fmt=auto&app=138&f=JPEG?w=650&h=433'
          }
        ]
      }]
    },
    {
      //一级
      id: 3,
      name: '红茶',
      data: [{
        //二级
        id: 4,
        name: '红茶',
        list: [
          //三级
          {
            id: 0,
            name: '祁门红茶',
            imgUrl: 'https://pic.rmb.bdstatic.com/16d33373e1ee9c3a7e12bdd8de7fcff0.jpeg'
          },
          {
            id: 1,
            name: '正山小种',
            imgUrl: 'https://img0.baidu.com/it/u=919074689,686123034&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          },
          {
            id: 3,
            name: '英德红茶',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.qdlsc.com%2FUpload%2F1615260906.jpeg&refer=http%3A%2F%2Fwww.qdlsc.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668328979&t=92140f562291aa35a127d9c150136bf2'
          },
          {
            id: 4,
            name: '川红',
            imgUrl: 'https://img1.baidu.com/it/u=260086960,2279279155&fm=253&fmt=auto&app=138&f=JPEG?w=720&h=500'
          },
          {
            id: 5,
            name: '宜红',
            imgUrl: 'https://img0.baidu.com/it/u=3003939901,36631760&fm=253&fmt=auto&app=138&f=JPEG?w=700&h=467'
          },
          {
            id: 5,
            name: '苏红和越红',
            imgUrl: 'https://img2.baidu.com/it/u=2142118983,1396681187&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          }
        ]
      }]
    },
    {
      //一级
      id: 4,
      name: '白茶',
      data: [{
        //二级
        id: 5,
        name: '白茶',
        list: [
          //三级
          {
            id: 0,
            name: '白牡丹',
            imgUrl: 'https://img2.baidu.com/it/u=3233585058,799597260&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          },
          {
            id: 1,
            name: '白毫银针',
            imgUrl: 'https://img2.baidu.com/it/u=2198812781,1956897819&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=326'
          },
          {
            id: 3,
            name: '贡眉',
            imgUrl: 'https://img0.baidu.com/it/u=3949091250,1954399626&fm=253&fmt=auto&app=138&f=JPEG?w=578&h=372'
          },
          {
            id: 4,
            name: '寿眉',
            imgUrl: 'https://img0.baidu.com/it/u=1662854408,1220643370&fm=253&fmt=auto&app=138&f=JPEG?w=535&h=500'
          }
        ]
      }]
    },
    {
      //一级
      id: 5,
      name: '普洱',
      data: [{
        //二级
        id: 6,
        name: '普洱',
        list: [
          //三级
          {
            id: 0,
            name: '饼茶',
            imgUrl: 'https://img1.baidu.com/it/u=2736534422,857648803&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333'
          },
          {
            id: 1,
            name: '沱茶',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fimgextra%2Fi1%2F12411736%2FT2GH2YXcRaXXXXXXXX_%21%2112411736.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668329379&t=cbab4f310d61e0d5826aaf2d63ab9ba0'
          },
          {
            id: 3,
            name: '砖茶',
            imgUrl: 'https://img1.baidu.com/it/u=1405857994,4203090576&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=503'
          },
          {
            id: 4,
            name: '柱茶',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fbao%2Fuploaded%2FO1CN01VvnxVZ1f7GhZ4m0s2_%21%216000000003959-0-yinhe.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668329432&t=d971af134e16c1eef1bd3d2a1b549a55'
          },
          {
            id: 5,
            name: '铁饼',
            imgUrl: 'https://img1.baidu.com/it/u=1261732135,3102544786&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          }
        ]
      }]
    },
    {
      //一级
      id: 6,
      name: '茶具',
      data: [{
        //二级
        id: 7,
        name: '茶具',
        list: [
          //三级
          {
            id: 0,
            name: '茶杯',
            imgUrl: 'https://img0.baidu.com/it/u=588003752,2654544099&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=329'
          },
          {
            id: 1,
            name: '茶宠',
            imgUrl: 'https://img1.baidu.com/it/u=2899686954,2272268307&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          },
          {
            id: 3,
            name: '煮水器电炉壶',
            imgUrl: 'https://img2.baidu.com/it/u=2532583899,1609177992&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          },
          {
            id: 4,
            name: '茶叶罐',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ff04e89427ba812616c03430d4c949341e2ee2033491d-CzsvPw_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668329702&t=55cfd0805a07167134b209df59e46a3a'
          },
          {
            id: 5,
            name: '品茗杯',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2.99114.com%2Fgroup10%2FM00%2F24%2FB9%2FrBADs1opW3eALpKcAAClrclmIG0892.jpg&refer=http%3A%2F%2Fimg2.99114.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668329733&t=4d0521d0b228b5406b7436febc359f8f'
          },
          {
            id: 6,
            name: '茶盘',
            imgUrl: 'https://img1.baidu.com/it/u=2007654545,1910095332&fm=253&fmt=auto&app=138&f=JPEG?w=479&h=320'
          },
          {
            id: 7,
            name: '茶壶',
            imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimgservice.suning.cn%2Fuimg1%2Fb2c%2Fimage%2F18moxQApZBbvxuG827gvoQ.jpg_800w_800h_4e&refer=http%3A%2F%2Fimgservice.suning.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668329558&t=9944d75bb4fc64e5c21b13240c74401f'
          },
          {
            id: 8,
            name: '香道',
            imgUrl: 'https://img0.baidu.com/it/u=1084591073,1600879161&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
          }
        ]
      }]
    }

    ]
  })

})


//查询商品数据接口
router.get('/api/goods/shopList', function (req, res, next) {
  //前端给后端的数据
  let [searchName, orderName] = Object.keys(req.query);
  let [name, order] = Object.values(req.query);

  if (!orderName || !order) {
    connection.query('select * from goods_list where name like "%' + name + '%" ', function (error, results) {
      res.send({
        code: 0,
        data: results
      })
    })
  } else {
    connection.query('select * from goods_list where name like "%' + name + '%" order by ' + orderName + ' ' + order + '', function (error, results) {
      res.send({
        code: 0,
        data: results
      })
    })
  }


})
//首页紫砂壶的数据
router.get('/api/index_list/5/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: [{
      id: 1,
      type: 'adList',
      data: [{
        id: 1,
        imgUrl: './images/zsh.jpg'
      },
      {
        id: 2,
        imgUrl: './images/zsh2.jpg'
      },
      {
        id: 3,
        imgUrl: './images/zsh3.jpg'
      }
      ]
    },
    {
      id: 2,
      type: 'likeList',
      data: [{
        id: 1,
        imgUrl: './images/zshlike.jpeg',
        name: '大师建盏-黑釉银滴盏',
        price: 450
      },
      {
        id: 2,
        imgUrl: './images/zshlike2.jpeg',
        name: '建盏茶漏（茶漏+茶托）',
        price: 99
      },
      {
        id: 3,
        imgUrl: './images/zshlike3.jpeg',
        name: '紫泥-六方佛光壶',
        price: 1580
      },
      {
        id: 4,
        imgUrl: './images/zshlike4.jpeg',
        name: '建阳红色芝麻毫建盏茶具',
        price: 399
      },
      ]
    }

    ]
  })
})
//首页绿茶的数据
router.get('/api/index_list/4/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: [{
      id: 1,
      type: 'adList',
      data: [{
        id: 1,
        imgUrl: './images/lc.jpg'
      },
      {
        id: 2,
        imgUrl: './images/lc2.png'
      }
      ]
    },
    {
      id: 2,
      type: 'likeList',
      data: [{
        id: 1,
        imgUrl: './images/lclike.jpeg',
        name: '口粮茶推荐：龙井1号250g',
        price: 68
      },
      {
        id: 2,
        imgUrl: './images/lclike2.jpeg',
        name: '品质茶推荐.2号茶150g',
        price: 88
      },
      {
        id: 3,
        imgUrl: './images/lclike3.jpeg',
        name: '品质龙井推荐.3号茶150g',
        price: 118
      },
      {
        id: 4,
        imgUrl: './images/lclike4.jpeg',
        name: '龙井破春系列80g罐装',
        price: 98
      }, {
        id: 5,
        imgUrl: './images/lclike5.jpeg',
        name: '2019春茶 明前龙井50g',
        price: 99
      },
      {
        id: 6,
        imgUrl: './images/lclike6.jpeg',
        name: '明前龙井·飞花系列 80g',
        price: 128
      }
      ]
    }

    ]
  })
})
//首页金骏眉的数据
router.get('/api/index_list/3/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: [{
      id: 1,
      type: 'adList',
      data: [{
        id: 1,
        imgUrl: './images/jjm.jpg'
      },
      {
        id: 2,
        imgUrl: './images/jjm2.jpg'
      }
      ]
    },
    {
      id: 2,
      type: 'likeList',
      data: [{
        id: 1,
        imgUrl: './images/jjmlike1.jpeg',
        name: '金骏眉-御品豪茗礼盒 250g',
        price: 128
      },
      {
        id: 2,
        imgUrl: './images/jjmlike2.jpeg',
        name: '金骏眉-如意小罐装180g',
        price: 158
      },
      {
        id: 3,
        imgUrl: './images/jjmlike3.jpeg',
        name: '金骏眉-特级黄芽单罐200g',
        price: 188
      },
      {
        id: 4,
        imgUrl: './images/jjmlike4.jpeg',
        name: '金骏眉-以茶为礼 200g',
        price: 188
      }, {
        id: 5,
        imgUrl: './images/jjmlike5.jpeg',
        name: '金骏眉-皇家典藏300g',
        price: 338
      },
      {
        id: 6,
        imgUrl: './images/jjmlike6.jpeg',
        name: '金骏眉-茶师王建波果蜜香100g',
        price: 258
      }
      ]
    }

    ]
  })
})
//首页铁观音的数据
router.get('/api/index_list/2/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: [{
      id: 1,
      type: 'adList',
      data: [{
        id: 1,
        imgUrl: './images/tgy.jpeg'
      },
      {
        id: 2,
        imgUrl: './images/tgy2.jpg'
      }
      ]
    },

    {
      id: 2,
      type: 'likeList',
      data: [{
        id: 1,
        imgUrl: './images/tgylike1.jpeg',
        name: '铁观音-红色花开富贵500g',
        price: 128
      },
      {
        id: 2,
        imgUrl: './images/tgylike2.jpeg',
        name: '铁观音-中国节420g',
        price: 99
      },
      {
        id: 3,
        imgUrl: './images/tgylike3.jpeg',
        name: '铁观音 金色御品豪茗茶具套装300g',
        price: 128
      },
      {
        id: 4,
        imgUrl: './images/tgylike4.jpeg',
        name: '谢宝海茶师亲制 | 半熟炭焙',
        price: 88
      }
      ]
    }

    ]
  })
})
//首页大红袍的数据
router.get('/api/index_list/1/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: [{
      id: 1,
      type: 'adList',
      data: [{
        id: 1,
        imgUrl: './images/dhp.jpeg'
      },
      {
        id: 2,
        imgUrl: './images/dhp2.jpg'
      }
      ]
    },
    {
      id: 2,
      type: 'likeList',
      data: [{
        id: 1,
        imgUrl: './images/dhplike1.jpeg',
        name: '口粮茶 铁盒装200g',
        price: 59
      },
      {
        id: 2,
        imgUrl: './images/dhplike2.jpeg',
        name: '武夷陈茶96g 罐装',
        price: 88
      },
      {
        id: 3,
        imgUrl: './images/dhplike3.jpeg',
        name: '远致肉桂96g 盒装',
        price: 59
      },
      {
        id: 4,
        imgUrl: './images/dhplike4.jpeg',
        name: '花果香肉桂96g 盒装',
        price: 99
      }
      ]
    }

    ]
  })
})
//首页推荐的数据
router.get('/api/index_list/0/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: {
      topBar: [
        { id: 0, label: '推荐' },
        { id: 1, label: '大红袍' },
        { id: 2, label: '铁观音' },
        { id: 3, label: '金骏眉' },
        { id: 4, label: '绿茶' },
        { id: 5, label: '紫砂壶' },
      ],
      data: [
        //这是swiper
        {
          id: 0,
          type: 'swiperList',
          data: [
            { id: 0, imgUrl: './images/swiper1.jpeg' },
            { id: 1, imgUrl: './images/swiper2.jpeg' },
            { id: 3, imgUrl: './images/swiper3.jpeg' }
          ]
        },
        //这是icons
        {
          id: 1,
          type: 'iconsList',
          data: [{
            id: 1,
            title: '自饮茶',
            imgUrl: './images/icons1.png'
          },
          {
            id: 2,
            title: '茶具',
            imgUrl: './images/icons2.png'
          },
          {
            id: 3,
            title: '茶礼盒',
            imgUrl: './images/icons3.png'
          },
          {
            id: 4,
            title: '领福利',
            imgUrl: './images/icons4.png'
          },
          {
            id: 5,
            title: '官方验证',
            imgUrl: './images/icons5.png'
          }
          ]
        },
        //爆款推荐
        {
          id: 3,
          type: 'recommendList',
          data: [{
            id: 1,
            name: '龙井1號铁罐250g',
            content: '鲜爽甘醇 口粮首选',
            price: '68',
            imgUrl: './images/recommend.jpeg'
          },
          {
            id: 2,
            name: '龙井1號铁罐250g',
            content: '鲜爽甘醇 口粮首选',
            price: '68',
            imgUrl: './images/recommend.jpeg'
          }
          ]
        },
        //猜你喜欢
        {
          id: 4,
          type: 'likeList',
          data: [{
            id: 1,
            imgUrl: './images/goods1.jpeg',
            name: '武夷山灰芽花香金骏眉3号',
            price: 128
          },
          {
            id: 2,
            imgUrl: './images/goods2.jpeg',
            name: '雨前珍稀白茶1号',
            price: 68
          },
          {
            id: 3,
            imgUrl: './images/goods3.jpg',
            name: '绿茶  远致龙井3号 150g 清爽甘醇',
            price: 118
          },
          {
            id: 4,
            imgUrl: './images/goods4.jpg',
            name: '明前春茶 绿茶 龙井破春系列80g罐装',
            price: 98
          },
          {
            id: 5,
            imgUrl: './images/goods5.jpeg',
            name: '九五兔毫建盏',
            price: 69
          },
          {
            id: 6,
            imgUrl: './images/goods6.jpeg',
            name: '【刘君】匠人建盏-油滴禅定杯',
            price: 399
          },
          {
            id: 7,
            imgUrl: './images/goods7.jpeg',
            name: '紫泥-六方佛光壶',
            price: 1580
          },
          {
            id: 8,
            imgUrl: './images/goods8.jpeg',
            name: '建阳红色芝麻毫建盏茶具',
            price: 399
          },
          {
            id: 9,
            imgUrl: './images/goods9.jpeg',
            name: '2016南糯山古树普洱生茶',
            price: 98
          },
          {
            id: 10,
            imgUrl: './images/goods10.jpeg',
            name: '黑砂快客旅行茶具',
            price: 288
          }
          ]
        }

      ]
    }
  })
});

module.exports = router;